<?php

class Article extends Model {

    private $category = NULL;
    private $gallery = NULL;

    public function __construct($data = NULL) {
        parent::__construct($data, 'articles');
    }

    public function getId() {
        return $this->getData('id');
    }

    public function getCategoryID() {
        return $this->getData('CategoryID');
    }

    public function getCategory() {
        if ($this->category == NULL) {
            $this->category = new ArticleCategory( intval($this->getCategoryID()) );
        }

        return $this->category;
    }

    public function setCategory($category) {
        $this->category = $category;
    }

    public function getTitle() {
        return $this->getData('ArticleTitle');
    }

    public function getTitleAlias() {
        return $this->getData('ArticleTitleAlias');
    }

    public function getLinkedTitle($options = NULL) {
		return $this->HTML->renderLink($this->getTitle(), $this->getURL(), $options);
    }

    public function getSummary() {
        if (defined("IN_CMS") && IN_CMS) {
            return $this->getData('ArticleSummary');
        }

        return kan_process_html($this->getData('ArticleSummary'));
    }

    public function getContent() {
        if (defined("IN_CMS") && IN_CMS) {
            return $this->getData('ArticleContent');
        }

        return kan_process_html($this->getData('ArticleContent'));
    }

    public function getAuthor() {
        return $this->getData('ArticleSource');
    }

    public function getImage() {
        return kan_fix_url($this->getData('ArticleImage'));
    }

    public function getImageThumbnail() {
        return kan_fix_url($this->getData('ArticleThumbnail'));
    }
	
	/**
	 * Generates the HTML required to display the Article Image
	 *
	 * @return string the html
	 */
	public function renderImage($options = NULL) {
		if( $this->getImage() != "" ) {
			return $this->HTML->renderImage( $this->getImage(), $options );
		}
		
		return NULL;
	}
	
	/**
	 * Generates the HTML required to display the Article Thumbnail Image
	 *
	 * @return string the html
	 */
	public function renderThumbnail($options = NULL) {
		return $this->HTML->renderImage( $this->getImageThumbnail(), $options );	
	}

	/**
	 * Returns the URL to the external Article Source
	 */
    public function getExternalURL() {
        return $this->getData('ArticleURL');
    }

	/**
	 * Returns the URL to the Article to be displayed. If an external URL has been
	 * specified, that will be returned, else an internal URL will be built and returned
	 */
    public function getURL() {
		
		$tag = $this->getCategory()->getCategoryAlias();
		$url = "../pages/articles.php?siteid=" . SITE_TAG . "&category=" . $tag . "&id=" . $this->getId();
		
		if( $this->getExternalURL() != "" ) {
			$url = $this->getExternalURL();	
			
		} else if (SEF_URLS) {
            $url = "../" . SITE_TAG . "/articles/" . $tag . "/" . $this->getTitleAlias();
        }
		
		if( defined("IN_CMS") && IN_CMS ) {
			return $url;	
		}

        return kan_fix_url($url);
    }

    public function getGalleryID() {
        return $this->getData('ArticleGallery');
    }

    public function getGallery() {
        if ($this->gallery == NULL) {
            $this->gallery = new Gallery($this->getGalleryID());
        }

        return $this->gallery;
    }

    public function getPostDate($format = "d-M") {
        return date($format, strtotime($this->getData('PostDate')));
    }

    public function isPublished() {
        return $this->getData('Published') == 1;
    }

    public function commentsAllowed() {
        return $this->getData('AllowComments') == 1;
    }

    public function getBreadCrumb($separator = "-") {
        // add home link
        $location = "<a href='" . kan_site_home() . "'>Home</a>";
		
		// get url for articles page
		$art_url = kan_fix_url('../pages/articles.php?siteid=' . SITE_TAG );

		// if using Friendly URLS then fix the url for the articles page
        if (SEF_URLS) {
            $art_url = kan_fix_url("../" . SITE_TAG . "/articles/" );
        }
		
		// add the articles page element
		$location .= " $separator <a href='$art_url'>Articles</a> ";

		// get the category for this article and build the link for it
        $category = $this->getCategory();
        $location .= " $separator <a href='" . $category->getURL() . "'>" . $category->getCategoryName() . "</a>";

		// add the element for the current article
        $location .= " $separator <a href='" . $this->getURL() . "'>" . $this->getTitle() . "</a>";

		// return the breadcrumb location
        return $location;
    }
	
	/**
	 * Returns an array of ArticleComment objects based on the supplied parameters
	 */
	public function getComments($start = 0, $total = NULL, $sortOrder = "ASC") {
		$db = $this->getDatabase();
		
		$query = sprintf("SELECT c.*, a.ArticleTitle FROM article_comments c " 
				. "INNER JOIN articles a ON a.id = c.ArticleID "
				. "WHERE c.ArticleID = %s ORDER BY c.id %s",
				$db->sanitizeInput($this->getId(),'int'),
				$sortOrder == "DESC" ? $sortOrder : "ASC" );
				
		
		if( $total != NULL ) {
			$query .= sprintf(" LIMIT %s, %s", $db->sanitizeInput($start,'int'), $db->sanitizeInput($total,'int'));
		}
		
		$db->query($query,true);
		$comments = array();
		
		for($i = 0; $i < $db->getResultCount(); $i++) {
            $ac = new ArticleComment($db->getRow($i));
            $ac->setArticle($this);
            
			array_push($comments, $ac );	
		}
		
		return $comments;
	}
	
	/**
	 * Returns an array of ArticleComment objects based on the supplied parameters
	 */
	public function getApprovedComments($start = 0, $total = NULL, $sortOrder = "ASC") {
		$db = $this->getDatabase();
		
		$query = sprintf("SELECT c.*, a.ArticleTitle FROM article_comments c " 
				. "INNER JOIN articles a ON a.id = c.ArticleID "
				. "WHERE ArticleID = %s AND Approved = 1 ORDER BY c.id %s",
				$db->sanitizeInput($this->getId(),'int'),
				$sortOrder == "DESC" ? $sortOrder : "ASC" );
		
		if( $total != NULL ) {
			$query .= sprintf(" LIMIT %s, %s", $db->sanitizeInput($start,'int'), $db->sanitizeInput($total,'int'));
		}
		
		$db->query($query,true);
		$comments = array();
		
		for($i = 0; $i < $db->getResultCount(); $i++) {
			$ac = new ArticleComment($db->getRow($i));
            $ac->setArticle($this);
            
			array_push($comments, $ac );	
		}
		
		return $comments;
	}
	
	/**
	 * Not implemented so return 0 for now
	 */
	public function getCommentCount($approvedOnly = true) {
		$db = $this->getDatabase();
		
		$app_cond = $approvedOnly ? " AND Approved = 1 " : "";
		
		$query = sprintf("SELECT count(id) AS cnt FROM article_comments WHERE ArticleID = %s $app_cond",
					$db->sanitizeInput( $this->getId(), 'int') );
		
		$row = $db->query($query)->getRow();
		return $row['cnt'];
	}
}
?>
